package com.ikas.ai.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取图片属性
 * @author HXH
 */
public class ImageAttributeUtil {

    private static Logger logger = LoggerFactory.getLogger(ImageAttributeUtil.class);
    public static final String HEIGHT = "height";
    public static final String WIDTH = "width";

    /**
     * 根据图片Base64获得图片高度宽度
     * @param imageBase64
     * @return Map<String, Object>
     * @throws IOException
     */
    public static Map<String, Integer> getImageHeightWidth(String imageBase64) {
        final Base64.Decoder decoder = Base64.getDecoder();
        byte[] decoderBytes = decoder.decode(imageBase64);
        return getImageHeightWidth(decoderBytes);
    }

    /**
     * 根据图片字节获得图片高度宽度
     * @param imageBytes
     * @return Map<String, Integer>
     * @throws IOException
     */
    public static Map<String, Integer> getImageHeightWidth(byte[] imageBytes) {
        try {
            Map<String, Integer> paramMap = new HashMap<String, Integer>();
            InputStream inStream = null;
            try {
                inStream = new ByteArrayInputStream(imageBytes);
                BufferedImage image = ImageIO.read(inStream);
                int height = image.getHeight();
                int width = image.getWidth();
                paramMap.put(HEIGHT, height);
                paramMap.put(WIDTH, width);
            } finally {
                closeInputStream(inStream);
            }
            return paramMap;
        } catch (IOException e) {
            logger.error(String.format("getImageHeightWidth throw exception: %s", e.getMessage()), e);
        }
        return null;
    }

    /**
     * 关闭文件流
     * @param in
     */
    private static void closeInputStream(Object in) {
        if (in != null) {
            try {
                if (in instanceof InputStream) {
                    ((InputStream) in).close();
                } else if (in instanceof MemoryCacheImageInputStream) {
                    ((MemoryCacheImageInputStream) in).close();
                }
            } catch (IOException e) {
                logger.error("InputStream close failure. ", e);
            }
        }
    }
}
